package xyz.jcat.biz.service.common;

import org.springframework.web.servlet.HandlerInterceptor;
import xyz.jcat.common.auth.AuthConst;
import xyz.jcat.common.auth.UserContextHolder;
import xyz.jcat.common.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader(AuthConst.HEADER_USER_ID);
        if(StringUtils.isNotBlank(userId)) {
            UserContextHolder.getInstance().setUserId(Long.valueOf(userId));
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.getInstance().clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
